<?php
if(!interface_exists('XSession', false)){
	require_once(XFRAMEWORK_DIR.'/core/mvc/http/XSession.php');
}
class XServletSession implements XSession{
	private static $instance = null;
	private $started = false;
	
	private function __construct(){
		
	}
	
	/**
	 * @return XServletSession
	 */	
	static function singleton() {
		if (!self::$instance) {
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	/**
	 * @return bool
	 */	
	public function destroy(){
		if($this->started){
			$this->started = !session_destroy();
			if(!$this->started){
				XEventContext::singleton()->publish(new XSessionDestroyEvent($this));
			}
			return !$this->started;
		}
		return true;
	}
	
	/**
	 * @return mixed
	 */		
	public function get($key){
		$this->start();
		return x_array_get($_SESSION, $key);
	}
	
	/**
	 * @return XServletSession
	 */	
	public function set($key, $value){
		$this->start();
		x_array_set($_SESSION, $key, $value, true);
		return $this;
	}
	
	/**
	 * @return array
	 */	
	public function getAll(){
		$this->start();
		return $_SESSION;
	}
	
	/**
	 * @return bool
	 */	
	public function start(){
		if(!$this->started){
			$this->started = session_start();
			if($this->started){
				XEventContext::singleton()->publish(new XSessionStartEvent($this));
			}
			return $this->started;
		}
		return true;
	}
	
	/**
	 * @return bool
	 */	
	public function started(){
		return $this->started;
	}
	
}
?>